<template>
  <div class="container">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="专利列表" name="list">
        <!-- 专利列表 -->
        <el-row class="">
          <el-col :span="13" align="left">
            <el-input clearable v-model="search.patentId" placeholder="专利号"
              style="width: 120px; margin-right: 15px"></el-input>
            <el-input clearable v-model="search.patentName" placeholder="专利名称"
              style="width: 120px; margin-right: 15px"></el-input>
            <el-input clearable v-model="search.patentUserName" placeholder="专利权人"
              style="width: 120px; margin-right: 15px"></el-input>
            <!--            <el-input clearable v-model="search.isContractSuccess" placeholder="合同中规定的成功" style="width: 150px; margin-right: 15px"></el-input>-->
            <el-select v-model="search.isContractSuccess" placeholder="合同中规定的成果" style="width: 150px"
              @change="changeLange" clearable>
              <el-option :label="item.itemText" :value="item.itemValue" :key="item.itemValue"
                v-for="item in chegnguoList" />
            </el-select>
            <el-button class="ordinary" @click="getTableList">搜索</el-button>
          </el-col>

          <el-col :span="11" align="right">
            <el-button class="unlock" @click="getUnlockBtn()" v-limit="'KJSL:KJCG:ZL:UNLOCK'">解锁</el-button>
            <el-button class="lock" @click="getLockBtn()" v-limit="'KJSL:KJCG:ZL:LOCK'">锁定</el-button>
            <el-button class="ordinary" @click="getExportBtn('1')" v-limit="'KJSL:KJCG:ZL:EXPERT'">批量导出</el-button>
            <el-button type="danger" @click="handleDetect()" v-limit="'KJSL:KJCG:ZL:DELETE'">批量删除</el-button>
            <el-button type="primary" @click="handleAdd()" v-limit="'KJSL:KJCG:ZL:ADD'">新增</el-button>
            <el-button type="primary" @click="downMbtwo()">下载模板</el-button>

            <el-upload class="upload-demo" action="/fastDfs/file/upload" :on-success="handleSuccesstwo" multiple
              :headers="headers" :limit="1" :show-file-list="false" :file-list="fileList">
              <!-- <a :href="File" download>下载模板</a> -->
              <el-button type="primary" @click="importEvaluatetwo()">导入</el-button>
            </el-upload>

          </el-col>
        </el-row>
        <div>
          <Table :loading="isLoading" :tableArr="tableDate" :pagination="pagination" :columns="columns"
           @selectItem="getCurrentList" :total="pagination.total" @delectTable="delectIds" @currentChange="currentChange" @sizeChange="sizeChange">
            <template #operate="{ row }">
              <el-button size="small" class="ordinary" v-show="row.updateFlag" :key="row.id + 'bj'" :disabled="row.isLock == 1"
                v-limit="'KJSL:KJCG:ZL:EDIT'" @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" class="ordinary" :key="row.id + 'bj'" @click="handleDetail(row)">详情</el-button>
              <el-button v-if="row.status == '待确认'" size="small" type="primary" :key="row.id + 'qr'"
                v-limit="'KJSL:KJCG:ZL:CONFIRM'" :disabled="row.isLock == 1" @click="handleConfirm(row)">确认</el-button>
            </template>
          </Table>
        </div>
      </el-tab-pane>

      <el-tab-pane label="专利质量评价" name="evaluate">
        <!-- 专利质量评价 -->
        <el-row class="">
          <el-col :span="16" align="left">
            <el-input clearable v-model="search2.unitName" placeholder="单位名称"
              style="width: 120px; margin-right: 15px"></el-input>
            <el-select clearable v-model="search2.pyear" placeholder="年份">
              <el-option :label="item.itemText" :value="item.itemValue" :key="item.itemValue" v-for="item in yearList1" />
            </el-select>
            <el-button class="ordinary" @click="getTable2List">搜索</el-button>
          </el-col>

          <el-col :span="8" align="right">
            <el-button class="ordinary" @click="getExportBtn('2')" v-limit="'KJSL:KJCG:ZL:EXPERT'">批量导出</el-button>
            <el-button type="primary" @click="downMb()">下载模板</el-button>

            <el-upload class="upload-demo" action="/fastDfs/file/upload" :on-success="handleSuccess" multiple
              :headers="headers" :limit="1" :show-file-list="false" :file-list="fileList">
              <!-- <a :href="File" download>下载模板</a> -->
              <el-button type="primary" @click="importEvaluate()" v-limit="'KJSL:KJCG:ZL:IMPORT'">导入</el-button>
            </el-upload>
            <!-- <el-button type="primary" @click="handleAdd()">导入</el-button> -->
          </el-col>
        </el-row>
        <div>
          <Table :loading="isLoading" :tableArr="table2Date" :pagination="pagination2" :columns="columns2"
            :total="pagination2.total" @delectTable="delectIds2" @currentChange="currentChange2" @sizeChange="sizeChange2">
            <template #operate="{ row }">
              <el-button size="small" class="ordinary"  v-show="row.updateFlag"  :key="row.id + 'bj'" :disabled="row.isLock == 1"
                v-limit="'KJSL:KJCG:ZL:EDIT'" @click="handleEdit2(row)">编辑</el-button>
              <el-button size="small" class="ordinary" :key="row.id + 'bj'" @click="handleDetail2(row)">详情</el-button>
            </template>
          </Table>
        </div>
      </el-tab-pane>
    </el-tabs>
    <!--新增修改-->
    <InfoDialog :dialogVisable1="infoDialog" :id="id" :flag="flag" @changeDialog="changeDialog"></InfoDialog>
    <InfoDialog2 :dialogVisable="infoDialog2" :detail2Data="detail2Data" @closeDialog2="closeDialog2"></InfoDialog2>
    <!--详情-->
    <InfoDialogxq :dialogVisable="infoDialogxq" :id="id" :flag="flag" @changeDialogxq="changeDialogxq"></InfoDialogxq>
    <InfoDialog2xq :dialogVisable="infoDialog2xq" :detail2Data="detail2Data" @closeDialog2xq="closeDialog2xq">
    </InfoDialog2xq>
  </div>
</template>
<script>
import * as proxy from '@/constants/proxy';
import request from '@/utils/request';
import { getDictionary, getUnit, } from "@/views/science/api/academic";
import { getConfirm, getDelect, getDetailById2, getExport, getExport2, getLock, getTable, getTable2, getUnlock, importMb, downMb, importMbtwo } from "@/views/science/api/patent";
import SelectOption from "@/views/science/components/selectOption/index.vue";
import Table from "@/views/science/components/table/table.vue";
import { Modals, tips } from "@/views/science/components/tips/tips";
import { ElMessage } from 'element-plus';
import moment from 'moment';
import { onMounted, reactive, toRefs, clearCache } from "vue";
import { useStore } from "vuex";
import InfoDialog from "./InfoDialog.vue";
import InfoDialog2 from "./InfoDialog2.vue";
import InfoDialogxq from "./InfoDialogxq.vue";
import InfoDialog2xq from "./InfoDialog2xq.vue";
import tableHead from "./tableHeader.json";

export default {
  components: {
    SelectOption,
    Table,
    InfoDialog,
    InfoDialog2,
    InfoDialogxq,
    InfoDialog2xq,
  },
  setup() {
    const store = useStore();
    // 发送请求
    onMounted(() => {
      // 获取数据字典
      getCodeList();
      // 获取单位
      getUnitList();
      // 列表信息table
      getTableList();
      affiliation()
    });

    const cookie = () => localStorage.getItem('token')
    let data = reactive({
      headers: {
        Authorization: 'Bearer ' + cookie(),
      },
      yearList1: [
        { itemText: '2026年', itemValue: '2026' },
        { itemText: '2025年', itemValue: '2025' },
        { itemText: '2024年', itemValue: '2024' },
        { itemText: '2023年', itemValue: '2023' },
        { itemText: '2022年', itemValue: '2022' },
        { itemText: '2021年', itemValue: '2021' },
        { itemText: '2020年', itemValue: '2020' },
        { itemText: '2019年', itemValue: '2019' },
        { itemText: '2018年', itemValue: '2018' },
        { itemText: '2017年', itemValue: '2017' },
      ],
      chegnguoList: [
        { itemText: '是', itemValue: '0' },
        { itemText: '否', itemValue: '1' },
      ],
      fileList: [],
      id: '',
      flag: 1,
      infoDialog: false,
      infoDialog2: false,
      infoDialogxq: false,
      infoDialog2xq: false,
      ids: [],
      ids2: [],
      activeName: 'list',
      pagination: { page: 1, limit: 10, total: 0}, //分页
      pagination2: { page: 1, limit: 10, total: 0}, //分页
      isLoading: false,
      unitNameList: [], //维护单位
      workList: [], //软著状态
      yearList: [],//专利类型
      tableDate: [],
      table2Date: [],
      columns: tableHead.compositionHeader,
      columns2: tableHead.compositionHeader2,
      search: {
        patentId: '',
        patentName: "",
        patentUserName: "",
        patentClassId: '',
        isContractSuccess: '',
      },
      search2: {
        pyear: '',
        unitName: "",
      },
      selectedRows: [],
      detail2Data: {},//第二页的详情数据
    });
    let changeLange = (id) => {
      let itemValue = data.chegnguoList.find(item => item.itemText == id).itemValue
      data.search.isContractSuccess = itemValue
    }

    //下载模板
    const downMb = () => {
      // downMb()
      let href = '/专利质量评价导入模板.xlsx'
      var a = document.createElement("a");
      a.href = href;
      a.download = `专利质量评价导入模板.xlsx`;
      a.style.display = "none";
      document.body.appendChild(a);
      a.click();
      a.remove()
    }
    //下载模板
    const downMbtwo = () => {
      // downMb()
      let href = '/专利批量导入模版.xlsx'
      var a = document.createElement("a");
      a.href = href;
      a.download = `专利批量导入模板.xlsx`;
      a.style.display = "none";
      document.body.appendChild(a);
      a.click();
      a.remove()
    }
    //切换列表
    const handleClick = (tab, event) => {
      if (data.activeName == 'evaluate') {
        getTable2List()
      }
    }
    const getTable2List = () => {
      data.isLoading = true
      getTable2(
        {
          current: data.pagination2.page,
          size: data.pagination2.limit,
          ...data.search2,
        }
      ).then(res => {
        data.table2Date = res.data.data.records
        console.log('getTable2List', data.table2Date);
        (data.pagination2.total = res.data.data.total);
        data.isLoading = false;
      }).catch(err => {
        data.isLoading = false;
      })
    }
    // 字典
    const affiliation = () => {
      request({
        url: proxy.CHECC_API_CMS + '/dictItem/codelist',
        method: 'post',
        data: ["KJSL_PATENT_TYPE"]
      }).then((res) => {
        console.log('字典', res);
        data.yearList = res.data.data.KJSL_PATENT_TYPE
      })
    }

    // 解锁
    let getUnlockBtn = async () => {
      if (data.ids.length == 1) {
        Modals("是否解锁选择内容", "提示", "warning")
          .then(async () => {
            let res = await getUnlock(data.ids);
            if (res.data.success) {
              tips("解锁成功", "success");
              getTableList();
            }
          })
          .catch(() => {
            console.log("点击了取消");
          });
      } else if (data.ids.length == 0) {
        tips("请选择", "warning");
      } else {
        tips("解锁功能不可批量操作", "warning");
      }
    };
    //  锁定
    let getLockBtn = async () => {
      if (data.ids.length == 1) {
        let flag = true
        console.log(data.selectedRows, 'selectedRows')
        data.selectedRows.forEach((obj) => {
          if (obj.status == '待确认') {
            flag = false
          }
        })
        if (!flag) {
          ElMessage({
            message: '请确认后再进行锁定',
            type: 'warning',
          })
          return
        }
        Modals("是否锁定选择内容", "提示", "warning")
          .then(async () => {
            let res = await getLock(data.ids);
            if (res.data.success) {
              tips("锁定成功", "success");
              getTableList();
            }
          })
          .catch(() => {
            console.log("点击了取消");
          });
      } else if (data.ids.length == 0) {
        tips("请选择", "warning");
      } else {
        tips("锁定功能不可批量操作", "warning");
      }
    };

    // 导出功能的实现
    let getExportBtn = (val) => {

      Modals('是否导出所选数据或者全部数据', '提示', 'warning').then(async () => {
        if (val == '1') {
          await getExport({
            current: data.pagination.page,
            size: data.pagination.limit,
            ...data.search,
            ids: data.ids,
          }, '专利列表')
        } else {
          await getExport2({
            current: data.pagination2.page,
            size: data.pagination2.limit,
            ...data.search2,
            ids: data.ids2,
          }, '专利质量评价')
        }


      }).catch(() => {
        console.log("点击了取消")
      })
    }
    // 确定当前流程
    let handleConfirm = async (row) => {
      Modals("是否确认当前流程", "提示", "warning")
        .then(async () => {
          // let res = await getConfirm({applyCode:row.applyCode});
          let res = await getConfirm({ id: row.id });
          if (res.data.success) {
            getTableList();
          }
        })
        .catch(() => { });
    };

    // 批量删除
    const handleDetect = async () => {
      if (data.ids.length) {
        Modals("是否删除选择内容", "提示", "warning")
          .then(async () => {
            let res = await getDelect(data.ids);
            if (res.data.success) {
              tips("删除成功", "success");
              getTableList();
            }
          })
          .catch(() => {
            console.log("点击了取消");
          });
      } else {
        tips("请选择", "warning");
      }
    };

    // 获取列表信息
    let getTableList = () => {
      data.isLoading = true
      getTable({
        current: data.pagination.page,
        size: data.pagination.limit,
        ...data.search,
      }).then((res) => {
        res.data.data.records.forEach(e => {
          if (e.status == 0) {
            e.status = '待确认'
          }
          if (e.status == 1) {
            e.status = '已确认'
          }
          if (e.status == 2) {
            e.status = '正常'
          }
          // 时间格式化--
          // if (e) {
          //   e.getEvent = moment(e.getEvent).format("YYYY-MM-DD");
          // }
          if (e.getEvent == null) {
            e.getEvent == '';
          } else {
            e.getEvent = moment(e.getEvent).format("YYYY-MM-DD");
          }

        });
        (data.tableDate = res.data.data.records),
          (data.pagination.total = res.data.data.total);
        data.isLoading = false;
      }).catch(err => {
        data.isLoading = false;
      })
    };

    // 分页
    let currentChange = (current) => {
      data.pagination.page = current;
      getTableList();
    };

    const sizeChange = (size) => {
      console.log(size)
      data.pagination.limit = size
      getTableList()
    }
    // 分页
    let currentChange2 = (current) => {
      data.pagination2.page = current;
      getTable2List();
    };

    const sizeChange2 = (size) => {
      console.log(size)
      data.pagination2.limit = size
      getTable2List()
    }
    const getCurrentList = (currentList) => {
      console.log(currentList, 'getCurrentList')
      data.selectedRows = currentList
    }
    // 获取ids
    let delectIds = (ids) => {
      let list = []
      data.tableDate.forEach(e => {
        if (ids.includes(e.id)) {
          list.push(e.applyCode)
        }
      })
      // data.ids = list  //原本用applyCode为唯一值
      data.ids = ids
    };
    // 获取ids2
    let delectIds2 = (ids) => {
      console.log('ids', ids);
      let list = []
      // data.table2Date.forEach(e =>{
      //   if(ids.includes(e.id)){
      //     list.push(e.applyCode)
      //   }
      // })
      data.ids2 = ids
    };

    // 人员列表
    let getUnitList = () => {
      getUnit({}).then((res) => {
        console.log('单位', res);
        data.unitNameList = res.data.data;
      });
    };

    // 著作级别
    let getCodeList = () => {
      getDictionary(["KJSL_ACADEMIC_WORK_LEVEL"]).then((res) => {
        data.workList = res.data.data.KJSL_ACADEMIC_WORK_LEVEL;
      });
    };

    // 新增
    let handleAdd = () => {

      data.flag = 1
      data.infoDialog = true
      // data.
    };
    // 编辑
    let handleEdit = (row) => {
      // console.log('row',row);
      data.flag = 2
      data.id = row.id
      // data.id = row.applyCode
      data.infoDialog = true
    }
    // 编辑2
    let handleEdit2 = (row) => {
      getDetailById2({ id: row.id }).then(res => {
        console.log('getDetailById2', res.data.data);
        data.detail2Data = res.data.data
      })
      data.infoDialog2 = true
    }
    // 编辑
    let handleDetail = (row) => {
      // console.log('row',row);
      data.flag = 2
      data.id = row.id
      // data.id = row.applyCode
      data.infoDialogxq = true
    }
    // 编辑2
    let handleDetail2 = (row) => {
      getDetailById2({ id: row.id }).then(res => {
        console.log('getDetailById2', res.data.data);
        data.detail2Data = res.data.data
      })
      data.infoDialog2xq = true
    }



    let changeDialog = (value) => {
      data.id = ''
      // data.flag = 1
      if (value) {
        data.pagination.page = 1
        getTableList()
      }
      // 分页刷新列表
      data.infoDialog = false
    }
    let closeDialog2 = (value) => {
      if (value) {
        data.pagination2.page = 1
        getTableList2()
      }
      // 分页刷新列表
      data.infoDialog2 = false
    }
    let changeDialogxq = (value) => {
      data.id = ''
      // data.flag = 1
      if (value) {
        data.pagination.page = 1
        getTableList()
      }
      // 分页刷新列表
      data.infoDialogxq = false
    }
    let closeDialog2xq = (value) => {
      if (value) {
        data.pagination2.page = 1
        getTableList2()
      }
      // 分页刷新列表
      data.infoDialog2xq = false
    }
    //导入
    const importEvaluate = () => {

    }
    const handleSuccess = (response, file, fileList) => {
      console.log('importMb',);
      if (response.code == 200) {
        const formData = new FormData();
        formData.append('file', file.raw);
        importMb(formData).then(res => {
          if (res.data.code == 200) {
            ElMessage.success('模板导入成功')
            getTable2List();
          }
        })
        data.fileList = []
      }

    }
    //导入
    const importEvaluatetwo = () => {

    }
    const handleSuccesstwo = (response, file, fileList) => {
      console.log('importMb',);
      if (response.code == 200) {
        const formData = new FormData();
        formData.append('file', file.raw);
        importMbtwo(formData).then(res => {
          if (res.data.code == 200) {
            ElMessage.success('模板导入成功')
            getTable2List();
          }
        })
        data.fileList = []
      }

    }
    // const File = new URL('/public/专利质量评价导入模板20231026.xlsx.xlsx', import.meta.url).href
    return {
      ...toRefs(data),
      downMb,
      downMbtwo,
      // File,
      store,
      handleEdit,
      handleEdit2,
      handleAdd,
      changeDialog,
      getTableList,
      getLockBtn,
      getExportBtn,
      getUnlockBtn,
      getCurrentList,
      delectIds,
      delectIds2,
      handleConfirm,
      handleDetect,
      handleClick,
      affiliation,
      importEvaluate,
      handleSuccess,
      importEvaluatetwo,
      handleSuccesstwo,
      closeDialog2,
      getTable2List,
      currentChange,
      currentChange2,
      sizeChange,
      sizeChange2,
      changeDialogxq,
      closeDialog2xq,
      handleDetail,
      handleDetail2,
      changeLange,
    };
  },
};
</script>
<style lang="scss" scoped>
.container {
  background-color: white;
  padding: 20px;
}

.upload-demo {
  display: inline-block;
  // width: 80px;
  margin: 0 10px;
}
</style>
